<template>
	<PageLayout title="控制飞机">

		<view
			style="padding: 6px; display: flex;border-radius: 10px;background-color: #ffffff;align-items: center;margin: 4px;border: 1px #eaeaea solid;">
			<picker mode="selector" :range="droneIdList" @change="handlecurrentSelectDroneIdChange"
				style="display: flex;justify-content: center;align-items: center;width: 100%;">
				<view v-if="hasChooseDrone">{{ '无人机id：' + currentSelectDroneId}}</view>
				<view v-if="!hasChooseDrone">{{'请选择无人机' }}</view>
			</picker>
		</view>
		<view
			style="padding: 6px; display: flex;border-radius: 10px;background-color: #ffffff;align-items: center;margin: 4px;border: 1px #eaeaea solid;">
			<picker mode="selector" :range="routeNameAndId" range-key="routeName"
				@change="handlecurrentSelectRouteNameAndIdChange"
				style="display: flex;justify-content: center;align-items: center;width: 100%;">
				<view v-if="hasChooseRoute">
					{{currentSelectRouteNameAndId.id+'号路线:' +currentSelectRouteNameAndId.routeName}}
				</view>
				<view v-if="!hasChooseRoute">{{'请选择路线' }}</view>
			</picker>
		</view>

		<view v-if="telemetryData!=null" style="width: 100%;height:calc(100% - 30px);">
			<!-- 地图容器 -->
			<map id="myMap" :key="mapKey" :latitude="telemetry_GPS_to_Gcj02[1]"
				:longitude="telemetry_GPS_to_Gcj02[0]" :markers="markers" :scale="21"
				style="width: 100%;height: 90%;">
			</map>
		</view>
		<!-- 右侧数据面板 -->
		<cover-view
			style="display: flex; top: 30%; flex-direction: column; justify-content: start; align-items: end; position: fixed; right: 0px; z-index: 999;">
			<cover-view
				style="display: flex; margin-right: 10px; background-color: rgba(0, 0, 0, 0.7); padding: 6px; border-radius: 10px; font-size: 12px; flex-direction: column; align-items: end; color: #eaeaea;">
				<cover-view style="margin-bottom:10px;">速度{{telemetryData.current_speed}}米每秒</cover-view>
				<cover-view style="margin-bottom:10px;">高度{{telemetryData.altitude}}米</cover-view>
				<cover-view>cpu负载{{telemetryData.system_usage}}%</cover-view>
			</cover-view>
		</cover-view>

		<!-- 左侧操作按钮 -->
		<cover-view
			style="display: flex; top: 30%; flex-direction: column; justify-content: start; position: fixed; color: #eaeaea; left: 10px; z-index: 999;">
			<cover-view
				style="height: 50px;padding: 6px; display: flex; border-radius: 10px; background-color: rgba(0, 0, 0, 0.7); align-items: center; margin-bottom: 10px;"
				@click="sendTakeOffOrder">
				<cover-image :src="isFly ? '/static/icons/take_off_red.png' : '/static/icons/take_off_white.png'"
					style="height: 20px; width: 20px; margin-right: 4px;" />
				<cover-view :style="{ fontSize: '14px', color: isFly ? '#ff0000' : '#eaeaea' }">起飞</cover-view>
			</cover-view>

			<cover-view
				style="height: 50px;padding: 6px; display: flex; border-radius: 10px; background-color: rgba(0, 0, 0, 0.7); align-items: center;"
				@click="sendLandOrder">
				<cover-image :src="isFly ? '/static/icons/land_white.png' : '/static/icons/land_black.png'"
					style="height: 20px; width: 20px; margin-right: 4px;" />
				<cover-view :style="{ fontSize: '14px', color: isFly ? '#eaeaea' : '#000000' }">降落</cover-view>
			</cover-view>
		</cover-view>



	</PageLayout>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		onUnmounted
	} from "vue";
	import PageLayout from "/pages/PageLayout/PageLayout.vue";
	import {
		wgs84ToGcj02
	} from "/utils/Utils";
	// 标记点数组（支持多个点）
	const markers = ref([]);

	let isFly = ref(false);

	const timer = ref(null);

	// 存储路线id和名称
	const routeNameAndId = ref([]);
	// 存储无人机ID列表
	const droneIdList = ref([]);
	//存储所选路线名称和id
	const currentSelectRouteNameAndId = ref({});
	//存储所选无人机id
	const currentSelectDroneId = ref();
	//存储是否选择无人机
	const hasChooseDrone = ref(false);
	//存储是否选择路线
	const hasChooseRoute = ref(false);
	//暂存无人机遥测数据
	const telemetryData = ref({
		"current_gps": {
			"latitude": 30.3096666,
			"longitude": 120.38607
		},
		"current_speed": 0.0,
		"altitude": 0.0,
		"system_usage": 0.0
	});

	const sendLandOrder = async () => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + `/monitor/putDroneOrder?drone_id=` + String(
					currentSelectDroneId.value), // 手动拼接参数
				method: 'PUT',
				data: ["land",Date.now()],
				header: {
					'Content-Type': 'application/json'
				}
			});
			if (response.statusCode === 200) {
				isFly.value = false;
				uni.showToast({
					title: '降落发送成功',
					icon: 'success'
				});
			} else {
				console.error('降落发送失败，状态码:', response.statusCode);
				uni.showToast({
					title: '降落发送失败',
					icon: 'error'
				});
			}
		} catch (error) {
			// 更详细的错误捕获
			console.error('请求异常:', {
				message: error.errMsg || error.message,
				code: error.errno || error.code,
				stack: error.stack
			});

			uni.showToast({
				title: `请求异常：${error.errMsg || error.message}`,
				icon: 'none',
				duration: 3000
			});
		}
	};

	const sendTakeOffOrder = async () => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + `/monitor/putDroneOrder?drone_id=` + String(
					currentSelectDroneId.value), // 手动拼接参数
				method: 'PUT',
				data: ["take_off",currentSelectRouteNameAndId.value.id,Date.now()],
				header: {
					'Content-Type': 'application/json'
				}
			});
			if (response.statusCode === 200) {
				isFly.value = true;
				uni.showToast({
					title: '起飞发送成功',
					icon: 'success'
				});
			} else {
				console.error('起飞发送失败，状态码:', response.statusCode);
				uni.showToast({
					title: '起飞发送失败',
					icon: 'error'
				});
			}
		} catch (error) {
			// 更详细的错误捕获
			console.error('请求异常:', {
				message: error.errMsg || error.message,
				code: error.errno || error.code,
				stack: error.stack
			});

			uni.showToast({
				title: `请求异常：${error.errMsg || error.message}`,
				icon: 'none',
				duration: 3000
			});
		}
	};

	// 获取路线名与路线id
	const fetchActiveRouteNameAndIdList = async () => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + `/monitor/getActiveRoutes`,
				method: 'GET',
				header: {
					'Content-Type': 'application/json'
				}
			});

			if (response.statusCode === 200) {
				routeNameAndId.value = response.data.data;
			} else {
				console.error('请求失败，状态码:', response.statusCode);
				uni.showToast({
					title: `请求失败: ${response.statusCode}`,
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('请求异常:', {
				message: error.errMsg,
				code: error.errno,
				stack: error.stack
			});

			uni.showToast({
				title: `请求异常：${error.errMsg}`,
				icon: 'none',
				duration: 3000
			});
		}
	};

	// 获取无人机ID列表
	const fetchDroneIdList = async () => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + `/monitor/getDroneIdList`,
				method: 'GET',
				header: {
					'Content-Type': 'application/json'
				}
			});

			if (response.statusCode === 200) {
				droneIdList.value = response.data.data;
			} else {
				console.error('请求失败，状态码:', response.statusCode);
				uni.showToast({
					title: `请求失败: ${response.statusCode}`,
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('请求异常:', {
				message: error.errMsg,
				code: error.errno,
				stack: error.stack
			});

			uni.showToast({
				title: `请求异常：${error.errMsg}`,
				icon: 'none',
				duration: 3000
			});
		}
	};

	const handlecurrentSelectRouteNameAndIdChange = (e) => {
		const selectedIndex = e.detail.value;
		currentSelectRouteNameAndId.value = routeNameAndId.value[selectedIndex];
		hasChooseRoute.value = true;
	};

	const handlecurrentSelectDroneIdChange = (e) => {
		const selectedIndex = e.detail.value;
		currentSelectDroneId.value = droneIdList.value[selectedIndex];
		hasChooseDrone.value = true;
	};

const telemetry_GPS_to_Gcj02=ref([]);
	//获取无人机遥测数据
	const fetchTelemetryData = async () => {
		if (currentSelectDroneId.value != null) {
			try {
				const response = await uni.request({
					url: getApp().globalData.rootUrl + `/monitor/getTelemetry?drone_id=` + String(
						currentSelectDroneId.value),
					method: 'GET',
					header: {
						'Content-Type': 'application/json'
					}
				});

				if (response.statusCode === 200) {
					telemetryData.value = response.data.data;
					telemetry_GPS_to_Gcj02.value=wgs84ToGcj02(telemetryData.value.current_gps.longitude,telemetryData.value.current_gps.latitude);
					// telemetryData.value.current_gps.longitude=Gcj02GPS[0];
					// telemetryData.value.current_gps.latitude=Gcj02GPS[1];
				} else {
					console.error('请求失败，状态码:', response.statusCode);
					uni.showToast({
						title: `请求失败: ${response.statusCode}`,
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('请求异常:', {
					message: error.errMsg,
					code: error.errno,
					stack: error.stack
				});

				uni.showToast({
					title: `请求异常：${error.errMsg}`,
					icon: 'none',
					duration: 3000
				});
			}
		}
	};

	const mapKey = ref(0);
	const currentDroneRoute = ref({});
	//获取所选无人机当前路线
	const fetchDroneRoute = async () => {
		if (telemetryData.value != null && currentSelectDroneId.value != null) {
			try {
				console.log(telemetryData.value.route_id);
				markers.value = [];
				if(telemetryData.value.route_id>=0){
					const response = await uni.request({
						url: getApp().globalData.rootUrl + `/monitor/getRoute?route_id=` + String(
							telemetryData.value.route_id),
						method: 'GET',
						header: {
							'Content-Type': 'application/json'
						}
					});
					
					if (response.statusCode === 200) {
						currentDroneRoute.value = response.data.data;
						// mapKey.value++;
						for (const item of currentDroneRoute.value) {
							const Gcj02GPS=wgs84ToGcj02(item.longitude,item.latitude);
							const newMarker = {
								id: markers.value.length + 1, // 生成新的ID
								latitude: Gcj02GPS[1], // 新的纬度
								longitude: Gcj02GPS[0], // 新的经度
								iconPath: '/static/icons/gps_point.png', // 本地图标路径
								title: "路径点" + String(markers.value.length + 1),
								width: 15,
								height: 15
							};
							markers.value.push(newMarker);
						}
						const newMarker = {
							id: markers.value.length + 1,
							latitude: telemetry_GPS_to_Gcj02.value[1],
							longitude: telemetry_GPS_to_Gcj02.value[0],
							iconPath: '/static/icons/drone_blue.png',
							title: "无人机当前坐标",
							width: 15,
							height: 15
						};
						markers.value.push(newMarker);
					} else {
						console.error('请求失败，状态码:', response.statusCode);
						uni.showToast({
							title: `请求失败: ${response.statusCode}`,
							icon: 'none'
						});
					}
				}
				else{
					const newMarker = {
						id: markers.value.length + 1,
						latitude: telemetry_GPS_to_Gcj02.value[1],
						longitude: telemetry_GPS_to_Gcj02.value[0],
						iconPath: '/static/icons/drone_blue.png',
						title: "无人机当前坐标",
						width: 15,
						height: 15
					};
					markers.value.push(newMarker);
				}

			} catch (error) {
				console.error('请求异常:', {
					message: error.errMsg,
					code: error.errno,
					stack: error.stack
				});

				uni.showToast({
					title: `请求异常：${error.errMsg}`,
					icon: 'none',
					duration: 3000
				});
			}
		}
	};

	onMounted(() => {
		fetchDroneIdList();
		fetchActiveRouteNameAndIdList();
		timer.value = setInterval(() => {
			fetchTelemetryData();
			fetchDroneRoute();
		}, 1000);
	});

	onUnmounted(() => {
		if (timer.value) clearInterval(timer.value);
	});
</script>


<style lang="scss" scoped>

</style>